﻿@using Fluxor.Blazor.Web.Components;
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.ClientStore;
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits FluxorComponent
@inject Radzen.DialogService dialogService
@inject NotificationService notificationService
@inject IState<AddClientState> addClientState
@inject IDispatcher dispatcher

@switch (Credential?.CredentialType)
{
    case UserCredential.PWD:
        <PasswordCredential CredentialSaved="UpdatePassword" ></PasswordCredential>
        break;
    case UserCredential.OTP:
        <OTPCredential CredentialSaved="UpdatePassword" Credential="Credential"></OTPCredential>
        break;
}

@code {
    [Parameter]
    public string UserId { get; set; }
    [Parameter]
    public UserCredential Credential { get; set; }


    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            SubscribeToAction<UpdateUserCredentialSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.UserCredentialUpdated });
                dialogService.Close();
                StateHasChanged();
            });
        }
    }

    void UpdatePassword(UserCredential cred)
    {
        Credential.Value = cred.Value;
        if (Credential.CredentialType == UserCredential.OTP)
            Credential.OTPAlg = cred.OTPAlg;

        dispatcher.Dispatch(new UpdateUserCredentialAction { UserId = UserId, Credential = Credential });
    }
}